<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<head>
    <link rel="stylesheet" href="${APP_PATH}/static/layui/css/layui.css" type="text/css" />
    <style type="text/css">
        td .layui-form-select {
            margin-top: -5px;
        }

        /*设置 layui 表格中单元格内容溢出可见样式*/
        #tableGrid_materialBack_div .layui-table-view,
        #tableGrid_materialBack_div .layui-table-box,
        #tableGrid_materialBack_div .layui-table-body {
            overflow: visible;
            padding: 0 0 0 0;
            margin: 0 0 0 0; /* 根据实际情况调整 */
        }

        #tableGrid_materialBack_div .layui-table-cell {
            height: auto;
            overflow: visible;
        }
    </style>
</head>
<div id="yclMaterialBackPage" style="margin: 15px">
    <%--query tools--%><%--生产退料--%>
    <blockquote class="layui-elem-quote">
        <form class="layui-form" id="materialBackForm">
            <div class="layui-fluid">
                <div class="layui-row">
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">退料单号</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" v-model="queryParams.applyCode" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">物料编码</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" v-model="queryParams.materialCode" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">生产厂区</label>
                            <div class="layui-input-inline">
                                <%--<input type="text" class="layui-input" v-model="queryParams.areaName" />--%>
                                <select id="back_materialAreaCodeSelect" lay-filter="back_materialAreaCodeSelect"
                                        lay-search>
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal"
                                    @click="queryPageView">
                                <i class="layui-icon">&#xe615;</i>查询
                            </button>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm"
                                    @click="resetQueryParams">
                                <i class="layui-icon">&#xe669;</i>重置
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">机台</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" v-model="queryParams.device" />
                            </div>
                        </div>
                    </div>
                    <%--<div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">质检状态</label>
                            <div class="layui-input-inline">
                                <select id="materialCheckStateSelect" lay-filter="materialCheckStateSelect">
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </div>--%>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">申请日期</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" id="back_materialApplyTime">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </blockquote>

    <%-- table grid --%>
    <table id="tableGrid_materialBack_source" lay-filter="tableGridFilter_materialBack_source"></table>
    <%-- table grid toolbar --%>
    <iframe style="visibility:hidden;" id="myiframe_materialBack_source" name="myiframe_materialBack_source" src=""
            width=0 height=0></iframe>
    <%-- table grid toolbar --%>
    <script type="text/html" id="tableGridToolbar_materialBack_source">
        <div class="layui-btn-container">
            <button type="button" lay-event="printOther" class="layui-btn layui-btn-sm layui-btn-normal"><i
                    class="layui-icon">&#xe66d;</i>打印单据
            </button>
        </div>
    </script>
    <%-- table grid --%>
    <div id="tableGrid_materialBack_div">
        <table id="tableGrid_materialBack" lay-filter="tableGridFilter_materialBack"></table>
    </div>
    <%-- table grid toolbar --%>
    <script type="text/html" id="tableGridToolbar_materialBack">
        <div class="layui-btn-container">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add">
                <i class="layui-icon">&#xe654;</i>增行
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove">
                <i class="layui-icon">&#xe67e;</i>清除
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-checked" lay-event="push">
                <i class="layui-icon">&#xe605;</i>提交
            </button>
        </div>
    </script>
</div>
<script src="/wms/plugins/public_components/js/jquery-2.1.4.js"></script>
<script src="/wms/static/js/techbloom/LodopFuncs.js" charset="utf-8"></script>
<script>
    const context_path = '${APP_PATH}';
    const table = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate;

    //获取table的list集合
    let vm = new Vue({
        el: '#yclMaterialBackPage',
        data: {
            lineId: "",
            orgid: "",
            rcvInvCode: "",
            tableGridSource: null,
            tableGrid: null,
            tableGridList: [],
            locatorCodeList: [],
            areaList: [], // 厂区
            checkStateList: [{ id: "6", text: "合格" }, { id: "7", text: "不合格" }], // 质检状态
            queryParams: { //查询参数
                applyCode: "",
                materialCode: "",
                areaName: "",
                areaCode: "",
                device: "",
                applyTimeStart: "",
                applyTimeEnd: "",
                checkState: ""
            }
        },
        methods: {
            getDateStr(dayCount) {
                let dd = new Date();
                dd.setDate(dd.getDate() + dayCount); // 获取dayCount天后的日期
                let y = dd.getFullYear();
                let m = dd.getMonth() + 1; // 获取当前月份的日期
                if (m < 10) {
                    m = '0' + m;
                }
                let d = dd.getDate();
                if (d < 10) {
                    d = '0' + d;
                }
                return y + "-" + m + "-" + d;
            },
            resetSelect(data, domId) {
                let html = '';
                let list = data;
                for (let i = 0; i < list.length; i++) {
                    html += '<option value=' + list[i].id + '>' + list[i].text + '</option>';
                }
                let $id = $('#' + domId);
                $id.empty();
                $id.append('<option value="">请选择</option>');
                $id.append(html);
                form.render('select');
            },
            renderSelectOptions(data, settings) {
                settings = settings || {};
                let valueField = settings.valueField || 'id',
                    textField = settings.textField || 'text',
                    selectedValue = settings.selectedValue || "";
                let html = [];
                for (let i = 0, item; i < data.length; i++) {
                    item = data[i];
                    html.push('<option value="');
                    html.push(item[valueField]);
                    html.push('"');
                    if (selectedValue && item[valueField] == selectedValue) {
                        html.push(' selected="selected"');
                    }
                    html.push('>');
                    html.push(item[textField]);
                    html.push('</option>');
                }
                return html.join('');
            },
            initSelect(async, url, data, domId, callback) {
                let dataJson = { queryString: "", limit: 100, page: 1 };
                let json = $.extend({}, dataJson, data);
                let valueField = data.valueField || 'id',
                    textField = data.textField || 'text';
                $.ajax({
                    type: 'GET',
                    url: context_path + url,
                    data: json,
                    async: async,
                    dataType: "json",
                    success: function (res) {
                        let html = '';
                        let list = res.data;
                        if (!!callback) {
                            callback(list);
                        }
                        for (let i = 0; i < list.length; i++) {
                            html += '<option value=' + list[i][valueField] + '>' + list[i][textField] + '</option>';
                        }
                        let $id = $('#' + domId);
                        $id.empty();
                        $id.append('<option value="">请选择</option>');
                        $id.append(html);
                        form.render('select');
                    }
                });
            },
            // 生产厂
            initAreaList() {
                this.initSelect(true, '/ycl/baseinfo/basedata/plant/0', {
                    valueField: 'code',
                    textField: 'text'
                }, 'back_materialAreaCodeSelect', (list) => this.areaList = list);
            },
            initCheckStateList() {
                this.resetSelect(this.checkStateList, 'materialCheckStateSelect');
                // this.initSelect(true, '/BaseDicType/qc', {}, 'materialCheckStateSelect', (list) => this.checkStateList = list);
            },
            initApplyTime() {
                //日期时间选择器
                laydate.render({
                    elem: '#back_materialApplyTime'
                    , type: 'date'
                    , range: '~'
                    // , btns: ['confirm']
                    // , value: vm.queryParams.applyTimeStart + ' ~ ' + vm.queryParams.applyTimeEnd
                    , done: function (value, date, endDate) {
                        let dateTime = value.split(' ~ ');
                        vm.queryParams.applyTimeStart = dateTime[0];
                        vm.queryParams.applyTimeEnd = dateTime[1];
                    }
                });
            },
            getTableGridData(lineId) {
                $.ajax({
                    type: 'GET',
                    url: context_path + "/ycl/material/back/backList",
                    data: { lineId: lineId },
                    async: false,
                    dataType: "json",
                    success: function (res) {
                        vm.tableGridList = res.data;
                    }
                });
            },
            pushTableData(data) {
                $.ajax({
                    type: 'post',
                    url: context_path + "/ycl/material/back/push",
                    data: JSON.stringify(data),
                    async: false,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        if (res.code == 0) {
                            layer.msg(res.msg, { icon: 1 });
                            vm.initLocatorCodeList(vm.orgid, vm.rcvInvCode);
                            vm.getTableGridData(vm.lineId);
                            vm.tableGrid.reload({
                                data: vm.tableGridList
                                , toolbar: false
                            });
                        } else {
                            layer.msg(res.msg, { icon: 2 });
                        }
                    }
                });
            },
            initLocatorCodeList(factorycode, storeCode) {
                $.ajax({
                    type: 'get',
                    url: context_path + "/goods/getShelfByFactWareCode.do",
                    data: {
                        warehouseCode: storeCode,
                        factorycode: factorycode,
                        queryString: '',
                        pageSize: 999,
                        pageNo: 1
                    },
                    async: false,
                    dataType: "json",
                    // contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        vm.locatorCodeList = res.result
                    }
                });
            },
            initTableGridSource() {
                // vm.queryParams.applyTimeStart = vm.getDateStr(-7);
                // vm.queryParams.applyTimeEnd = vm.getDateStr(0);
                // this.getTableData();
                this.tableGridSource = table.render({
                    elem: '#tableGrid_materialBack_source'
                    , url: context_path + '/ycl/material/back/list'
                    , page: true
                    // , data: vm.tableList
                    , toolbar: '#tableGridToolbar_materialBack_source'
                    , id: "tableGridSet_materialBack_source"
                    , size: 'sm'
                    , defaultToolbar: []
                    , cols: [[
                        { type: 'radio' }
                        , { field: 'lineId', title: '行ID', width: 55 }
                        , { field: 'billno', title: '退料单号', width: 160 }
                        , { field: 'seq', title: '行号', width: 55 }
                        , { field: 'itemname', title: '物料编码', width: 110 }
                        , { field: 'itemdesc', title: '物料名称', width: 160 }
                        , { field: 'uom', title: '单位', width: 55 }
                        , { field: 'outBackQuantity', title: '领料出库数量', width: 110 }
                        , { field: 'qty', title: '退料数量', width: 80 }
                        , { field: 'lotno', title: '批次号', width: 160 }
                        , { field: 'fromInvDesc', title: '来源子库', width: 160 }
                        , { field: 'rcvInvDesc', title: '目标子库', width: 160 }
                        , { field: 'shopDesc', title: '生产厂区', width: 100 }
                        , { field: 'deviceDesc', title: '机台', width: 160 }
                        , { field: 'createdate', title: '申请日期', width: 145 }
                    ]]
                });
            },
            initTableGrid() {
                // vm.queryParams.applyTimeStart = vm.getDateStr(-7);
                // vm.queryParams.applyTimeEnd = vm.getDateStr(0);
                // this.getTableData();
                this.tableGrid = table.render({
                    elem: '#tableGrid_materialBack'
                    // , url: context_path + '/ycl/material/back/list'
                    // , data: vm.tableList
                    , data: []
                    , page: false
                    , limit: 99999
                    // , height: 500
                    // , toolbar: '#tableGridToolbar_materialBack'
                    , id: "tableGridSet_materialBack"
                    , size: 'sm'
                    , defaultToolbar: []
                    , cols: [[
                        { type: 'checkbox' }
                        , { field: 'lineId', title: '行ID', width: 55 }
                        // , { field: 'billno', title: '退料单号', width: 150 }
                        // , { field: 'seq', title: '行号', width: 55 }
                        , { field: 'itemname', title: '物料编码', width: 110 }
                        , { field: 'itemdesc', title: '物料名称', width: 160 }
                        , { field: 'lotno', title: '批次号', width: 180 }
                        , { field: 'uom', title: '单位', width: 55 }
                        , { field: 'outBackQuantity', title: '领料出库数量', width: 110 }
                        , { field: 'qty', title: '退料数量', width: 80 }
                        , {
                            field: 'inQuantity', title: '入库数量', width: 80, edit: 'text',
                            templet: (d) => d.inQuantity || 0
                        }
                        , {
                            field: 'boxAmount', title: '件数', width: 60, edit: 'text',
                            templet: (d) => d.boxAmount || 0
                        }
                        , {
                            field: 'checkState', title: '质检状态', width: 120, templet: function (d) {
                                let options = vm.renderSelectOptions(vm.checkStateList, {
                                    selectedValue: d.checkState
                                });
                                return '<select name="checkState" lay-filter="checkState"><option value="0">请选择</option>' + options + '</select>';
                            }
                        }
                        // , { field: 'fromInvDesc', title: '来源子库', width: 160 }
                        // , { field: 'rcvInvDesc', title: '目标子库', width: 160 }
                        , {
                            field: 'locatorCode', title: '库位', width: 160, templet: function (d) {
                                let options = vm.renderSelectOptions(vm.locatorCodeList, {
                                    selectedValue: d.locatorCode,
                                    valueField: 'code',
                                    textField: 'codename'
                                });
                                return '<select name="locatorCode" lay-filter="locatorCode" lay-search><option value="0">请选择</option>' + options + '</select>';
                            }
                        }
                        // , { field: 'shopDesc', title: '生产厂区', width: 100 }
                        // , { field: 'deviceCode', title: '机台', width: 120 }
                        // , { field: 'createdate', title: '申请日期', width: 145 }
                    ]]
                });
            },
            // 查询
            queryPageView() {
                // this.getTableData();
                vm.tableGridSource.reload({
                    where: vm.queryParams,
                    page: { curr: 1 }
                });
            },
            // 重置查询
            resetQueryParams() {
                vm.queryParams = {
                    applyCode: "",
                    materialCode: "",
                    areaName: "",
                    areaCode: "",
                    device: "",
                    applyTimeStart: "",
                    applyTimeEnd: "",
                    // applyTimeStart: vm.getDateStr(-7),
                    // applyTimeEnd: vm.getDateStr(0),
                    checkState: ""
                };
                $("#materialBackForm")[0].reset();
                this.queryPageView();
                // this.initApplyTime();
            },
            printOther(lineId, billno) {
                var frm = document.getElementById('myiframe_materialBack_source');
                frm.src = '/wms/ycl/material/back/toPrint?lineId=' + lineId + '&billno=' + billno;
                $(frm).load(function () {
                    LODOP = getLodop();
                    var strHtml = frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strHtml);
                    LODOP.PREVIEW();
                });
            }
        },
        created() {
        },
        mounted() {
            this.initCheckStateList();
            this.initTableGridSource();
            this.initTableGrid();
            this.initAreaList();
            this.initApplyTime();
        }

    })

    table.on('row(tableGridFilter_materialBack_source)', function (obj) {
        const checkData = obj.data;
        let oldData = table.cache['tableGridSet_materialBack'];
        vm.lineId = checkData.lineId;
        vm.orgid = checkData.orgid;
        vm.rcvInvCode = checkData.rcvInvCode;
        if (oldData.length > 0) {
            const oldLineId = oldData[0].lineId;
            if (checkData.lineId != oldLineId) {
                // layer.confirm('是否清空列表重新录入？', {}, function (index) {
                vm.initLocatorCodeList(checkData.orgid, checkData.rcvInvCode);
                vm.getTableGridData(checkData.lineId);
                if (vm.tableGridList.length != 0) {
                    vm.tableGrid.reload({
                        data: vm.tableGridList
                        , toolbar: false
                    });
                } else {
                    checkData.boxAmount = 0;
                    // checkData.lotno = "YDXCL191204";
                    // checkData.locatorCode = 0;
                    checkData.inQuantity = 0;
                    checkData.tempId = new Date().valueOf();
                    vm.tableGrid.reload({
                        data: [checkData]
                        , toolbar: '#tableGridToolbar_materialBack'
                    });
                }
                // layer.close(index);
                //选中行样式
                obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                //选中radio样式
                obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
                // }, function () {
                // });
            }
        } else {
            vm.initLocatorCodeList(checkData.orgid, checkData.rcvInvCode);
            vm.getTableGridData(checkData.lineId);
            if (vm.tableGridList.length != 0) {
                vm.tableGrid.reload({
                    data: vm.tableGridList
                    , toolbar: false
                });
            } else {
                checkData.boxAmount = 0;
                // checkData.lotno = "YDXCL191204";
                // checkData.locatorCode = 0;
                checkData.inQuantity = 0;
                checkData.tempId = new Date().valueOf();
                vm.tableGrid.reload({
                    data: [checkData]
                    , toolbar: '#tableGridToolbar_materialBack'
                });
            }
            //选中行样式
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            //选中radio样式
            obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
        }
    });

    table.on('toolbar(tableGridFilter_materialBack_source)', function (obj) {
        switch (obj.event) {
            case 'printOther':
                let selectData = table.checkStatus(obj.config.id).data;
                if (selectData.length == 0) {
                    layer.msg('请选择一行数据', { icon: 2 });
                    return;
                }
                vm.printOther(selectData[0].lineId, selectData[0].billno);
                break;
        }
    });

    table.on('toolbar(tableGridFilter_materialBack)', function (obj) {
        const checkStatusData = table.checkStatus(obj.config.id).data;
        let oldData;
        switch (obj.event) {
            case 'add': // 增行
                oldData = table.cache["tableGridSet_materialBack"];
                let checkData = $.extend({}, oldData[0]);
                checkData.boxAmount = 0;
                checkData.checkState = "";
                checkData.locatorCode = "";
                checkData.inQuantity = 0;
                // checkData.lotno = "YDXCL191204";
                checkData.tempId = new Date().valueOf();
                table.reload('tableGridSet_materialBack', {
                    data: [...[checkData], ...oldData]
                });
                break;
            case 'remove': // 清除
                if (checkStatusData.length == 0) {
                    layer.msg('请选择行数据', { icon: 2 });
                    return;
                }
                oldData = table.cache['tableGridSet_materialBack'];
                for (let data of checkStatusData) {
                    for (let i = 0; i < oldData.length; i++) {
                        if (oldData[i].tempId === data.tempId) {
                            oldData.splice(i, 1);
                            break;
                        }
                    }
                }
                table.reload('tableGridSet_materialBack', {
                    data: oldData
                });
                break;
            case 'push': // 退货单
                oldData = table.cache['tableGridSet_materialBack'];
                if (oldData.length == 0) {
                    layer.msg('请先添加数据', { icon: 2 });
                    return;
                }
                for (let x of oldData) {
                    if (x.inQuantity == 0) {
                        layer.msg('入库数量不能为0', { icon: 2 });
                        return;
                    }
                    if (!x.checkState || x.checkState == 0) {
                        layer.msg('请选择质检状态', { icon: 2 });
                        return;
                    }
                    if (!x.locatorCode || x.locatorCode == 0) {
                        layer.msg('请选择库位', { icon: 2 });
                        return;
                    }
                }
                vm.pushTableData(oldData)
                break;
        }
    });

    /*table.on('tool(tableGridFilter_materialBack)', function (obj) {
        const checkStatusData = obj.data, tr = obj.tr;
        switch (obj.event) {
            case "checkState":
                let select = tr.find("select[name='checkState']");
                if (select) {
                    let selectedVal = select.val();
                    if (!selectedVal) {
                        layer.tips("请选择一个状态", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
                    }
                    let oldData = table.cache['tableGridSet_materialBack'];
                    for (let old of oldData) {
                        if (old.tempId == checkStatusData.tempId) {
                            old.checkState = selectedVal
                            break;
                        }
                    }
                    table.reload('tableGridSet_materialBack', {
                        data: oldData
                    });
                }
                break;
        }
    });*/

    // 监听编辑单元格
    table.on('edit(tableGridFilter_materialBack)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        let value = obj.value;
        let field1 = obj.field;
        if (field1 == "boxAmount" || field1 == "inQuantity") {
            value = parseFloat(value);
            if (isNaN(value)) {
                value = 0;
            }
        }
        obj.update({ [field1]: value });
    });

    //监听select
    form.on('select(back_materialAreaCodeSelect)', function (data) {
        vm.queryParams.areaCode = data.value;
    });

    //监听select
    form.on('select(materialCheckStateSelect)', function (data) {
        vm.queryParams.checkState = data.value;
    });

    form.on('select(checkState)', function (data) {
        let elem = $(data.elem);
        let trElem = elem.parents('tr');
        let tableData = table.cache['tableGridSet_materialBack'];
        // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
        tableData[trElem.data('index')][elem.attr('name')] = data.value;
    });

    form.on('select(locatorCode)', function (data) {
        let elem = $(data.elem);
        let trElem = elem.parents('tr');
        let tableData = table.cache['tableGridSet_materialBack'];
        // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
        tableData[trElem.data('index')][elem.attr('name')] = data.value;
    });

</script>